var DELAY = 1000;
var sssTimeout;
var options = {
		buyAttack:false,
		buyDefense:false,
		buyHealth:false,
		buyEnergy:false,
		buyStamina:false,
		autostart:false
};

/************************
 * 		Spinner			*
 ************************/

function sss_spin(){
	if(document.getElementById("skill-point-factory-offer")===null){
		sssTimeout = setTimeout(sss_spin,DELAY);
	}
	else{
		if(spinsLeft()>0){
			try{
				$('.spin-btn-active').click();
				sssTimeout = setTimeout(sss_check,DELAY);
			}
			catch(e){console.log("Error spinning button");}
		}
		else{
			logDeal("All spins used, closing SkillStir.");
			$('.pop_bg').each( function(){
				var id = this.id;
				MW.Popup.hide( id.substr( id.lastIndexOf("_") +1 ) );
			});
		}
	}
}

/*
 * "<a class="sexy_button_new medium gold sexy_coin_new disabled" style="min-width: 90px" onclick="return false;" href=""><span><span>RP</span></span></a>"
 */

function sss_check(){
	try{
		var buyButton = document.getElementsByClassName("buy-deal-btn-cont")[0];
		var dealInfo = buyButton.firstChild.outerHTML;
		dealInfo = dealInfo.split("?")[1].split("&quot")[0];
		var dealKeyValues = dealInfo.split("&amp;");
		var deal = {};
		for(var i = 0; i < dealKeyValues.length; i++){
			var kv = dealKeyValues[i].split("=");
			deal[kv[0]]=kv[1];
		}
		true;
		if(deal.skillType!==undefined && deal.dealCost!==undefined){
			if(sss_shouldBuyDeal(deal)){
				buyButton.children[0].click();
				logDeal(deal);
			}
			sssTimeout = setTimeout(sss_spin,DELAY);
			return;
		}
	}
	catch(e){}
	sssTimeout = setTimeout(sss_check,DELAY);
}
	
function sss_shouldBuyDeal(deal){
	if(deal.dealCost==="7"){
		return deal.skillType==="1" && options.buyHealth;
	}
	else if(deal.dealCost==="21"){
		return ((deal.skillType==="2" && options.buyEnergy)
				|| (deal.skillType==="3" && options.buyStamina)
				|| (deal.skillType==="4" && options.buyAttack)
				|| (deal.skillType==="5" && options.buyDefense));
	}
	else{
		return false; 
	}
}

function sss_dealNbToSkillName(nb){
	if(nb=="1") return "health";
	if(nb=="2") return "energy";
	if(nb=="3") return "stamina";
	if(nb=="4") return "attack";
	if(nb=="5") return "defense";
	return "???";
}

function spinsLeft(){
	try{
		return parseInt(document.getElementsByClassName("spins-left-count")[0].innerHTML);
	}
	catch(e){
		console.log("Error getting spins left");
		return 0;
	}
}

function logDeal(deal){
	var logdiv = document.getElementById("sss_log");
	logdiv.innerHTML = "<span>Bought "+sss_dealNbToSkillName(deal.skillType)+" for "+deal.dealCost+" RPs.<br/>"+logdiv.innerHTML;
}

/************************
 * 	Open MW SkillStir	*
 ************************/

/*
 * Start the mafia wars spinner
 */
function startMWSpinner(){
	var url = 'remote/'+getIntURL("SkillPointFactory","showOfferPopup");
	do_ajax('popup_fodder',url, 1, 0);
}

/*
 * Thanks Luke :)
 */
function getIntURL(controller, action, city, person) {
	var params = [
	              'xw_controller=' + (controller || 'index'), 
	              'xw_action=' + (action || 'view'), 
	              'xw_city=' + (city || 7), 
	              'xw_person=' + (person || User.id)];
	return 'html_server.php?' + params.join('&');
}


/************************
 * 		GUI				*
 ************************/

var sss_html = 
	'<div><span style="float:left">'+
	'<input onchange="sss_uiToSettings();" type="checkbox" id="sss_buyAttack"/> buy attack (for 21 RPs)'+
	'<br/><input onchange="sss_uiToSettings();" type="checkbox" id="sss_buyDefense"/> buy defense (for 21 RPs)'+
	'<br/><input onchange="sss_uiToSettings();" type="checkbox" id="sss_buyHealth"/> buy health (for 7 RPs)'+
	'<br/><input onchange="sss_uiToSettings();" type="checkbox" id="sss_buyEnergy"/> buy energy (for 21 RPs)'+
	'<br/><input onchange="sss_uiToSettings();" type="checkbox" id="sss_buyStamina"/> buy stamina (for 21 RPs)'+
	'<br/><input onchange="sss_uiToSettings();" type="checkbox" id="sss_autostart"/> autostart'+
	'</span>'+
	'<span style="float:right">'+
	'<img id="sss_start" width="25px" height="25px" src="https://avngr.googlecode.com/svn/img/ctplay.png"/>'+
	'</span></div>'+
	'<div id="sss_log" style="padding:4px; width:300px; height:200px; overflow:auto;"></div>';

function makeDiv(){
	if(document.getElementById("sss_main")!==null){
		return;
	}
	var div = document.createElement("div");
	div.id = 'sss_main';
	div.innerHTML = sss_html;
	$('#popup_fodder').append(div);
	
	document.getElementById("sss_start").onclick = sss_start;
	
	$('#sss_main').dialog({ title: "SkillStirSpinner v1.0", close: sss_close,width: 400, position: ['center',100]});
}

function sss_start(){
	$('#sss_start').toggle();
	sss_spin();
}

function sss_close(){
	clearTimeout(sssTimeout);
	$('#sss_main').remove();
}

/************************
 * 		Options			*
 ************************/

var storage;
function sss_initStorage(){
	console.log("initializing storage");
	try {
		if (localStorage.getItem) {
			storage = localStorage;
		} else if (window.localStorage.getItem) {
			storage = window.localStorage;
		}
	} catch(e) {}
}

function sss_readSettings(){
	console.log("reading settings");
	if (storage.getItem("sss_options")) {
		var tempOptions = JSON.parse(storage.getItem("sss_options"));
		if(options.length == tempOptions.length){
			options = tempOptions;
		}
	}
	sss_writeSettings();
}

function sss_writeSettings(){
	storage.setItem("sss_options", JSON.stringify(options));
}

function sss_settingsToUi(){
	$('#sss_autostart').attr('checked',options.autostart);
	$('#sss_buyAttack').attr('checked',options.buyAttack);
	$('#sss_buyDefense').attr('checked',options.buyDefense);
	$('#sss_buyHealth').attr('checked',options.buyHealth);
	$('#sss_buyEnergy').attr('checked',options.buyEnergy);
	$('#sss_buyStamina').attr('checked',options.buyStamina);
}

function sss_uiToSettings(){
	options.autostart = $('#sss_autostart').attr('checked');
	options.buyAttack = $('#sss_buyAttack').attr('checked');
	options.buyDefense = $('#sss_buyDefense').attr('checked');
	options.buyHealth = $('#sss_buyHealth').attr('checked');
	options.buyEnergy = $('#sss_buyEnergy').attr('checked');
	options.buyStamina = $('#sss_buyStamina').attr('checked');
	sss_writeSettings();
}

javascript: (function() {
	console.log("SkillStirSpinner started");
	startMWSpinner();
	makeDiv();
	sss_initStorage();
	sss_readSettings();
	sss_settingsToUi();
	if(options.autostart){
		sss_start();
	}
}());